{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-03-03T05:31:09.896582Z",
     "start_time": "2025-03-03T05:31:09.702149Z"
    }
   },
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-03-03T06:46:49.035894Z",
     "start_time": "2025-03-03T06:46:49.024685Z"
    }
   },
   "cell_type": "code",
   "source": [
    "index1 = pd.MultiIndex.from_arrays([['a','a','a','b','b','b','c','c','c','d','d','d'],[0,1,2,0,1,2,0,1,2,0,1,2]],names=['cloth','size'])  # 创建了一个多级索引index1\n",
    "\"\"\"\n",
    "第一个参数 [['a','a','a','b','b','b','c','c','c','d','d','d'],[0,1,2,0,1,2,0,1,2,0,1,2]]：这是一个包含两个列表的列表，每个内部列表代表一个索引层级。第一个列表 ['a','a','a','b','b','b','c','c','c','d','d','d'] 是第一级索引，第二个列表 [0,1,2,0,1,2,0,1,2,0,1,2] 是第二级索引。两个列表的长度必须相同，因为它们要一一对应组合成多级索引。\n",
    "第二个参数 names=['cloth', 'size']：这是一个可选参数，用于为每个索引层级指定名称。这里将第一级索引命名为 'cloth'，第二级索引命名为 'size'。\n",
    "\"\"\"\n",
    "ser_obj = pd.Series(np.random.randn(12),index=index1)\n",
    "\"\"\"\n",
    "第一个参数 np.random.randn(12)：使用 numpy 库的 random.randn 函数生成一个包含 12 个服从标准正态分布的随机数的数组，这些随机数将作为 Series 对象的值。\n",
    "第二个参数 index=index1：指定 Series 对象的索引为之前创建的多级索引 index1。这样，Series 对象的每个值都与多级索引中的一个组合相对应。\n",
    "\"\"\"\n",
    "ser_obj"
   ],
   "id": "dc1789506ff7c359",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "cloth  size\n",
       "a      0      -1.518355\n",
       "       1       1.438618\n",
       "       2       2.718638\n",
       "b      0       1.353773\n",
       "       1       0.675709\n",
       "       2       1.915683\n",
       "c      0       0.913146\n",
       "       1       0.082567\n",
       "       2       0.407188\n",
       "d      0       0.467908\n",
       "       1      -0.816552\n",
       "       2      -0.089726\n",
       "dtype: float64"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-03-03T07:07:24.822403Z",
     "start_time": "2025-03-03T07:07:24.817847Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(type(ser_obj))\n",
    "print('-'*50)\n",
    "df_obj = ser_obj.unstack(level=0)  # 将Series对象转换为DataFrame对象\n",
    "\"\"\"\n",
    "unstack() 的核心作用是将多级索引中的某一级别索引转换为列索引，从而实现数据从长格式到宽格式的转换。这种转换在数据处理和分析中非常常见，能够让数据更适合进行特定的统计分析或可视化展示。\n",
    "原始的 Series 对象 ser_obj：它具有两级索引，第一级索引是 cloth（包含 'a', 'b', 'c', 'd'），第二级索引是 size（包含 0, 1, 2）。数据以长格式存储，每个值对应一个多级索引的组合。\n",
    "unstack() 操作：默认情况下，unstack() 会将最内层的索引（这里是 size）转换为列索引。\n",
    "转换后的 DataFrame 对象 df_obj：cloth 索引变为行索引，size 索引变为列索引，数据以宽格式存储。这样，原本在 Series 中通过多级索引来区分的数据，在 DataFrame 中以行列结构呈现，更加直观和便于分析。\n",
    "unstack() 方法可以接受一个参数 level，用于指定要转换为列索引的索引级别。默认值为 -1，表示最内层的索引。例如：\n",
    "\"\"\"\n",
    "print(df_obj)\n",
    "print('-'*50)\n",
    "print(type(df_obj))"
   ],
   "id": "6a36eeba56c1421c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.series.Series'>\n",
      "--------------------------------------------------\n",
      "cloth         a         b         c         d\n",
      "size                                         \n",
      "0     -1.518355  1.353773  0.913146  0.467908\n",
      "1      1.438618  0.675709  0.082567 -0.816552\n",
      "2      2.718638  1.915683  0.407188 -0.089726\n",
      "--------------------------------------------------\n",
      "<class 'pandas.core.frame.DataFrame'>\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-03-03T07:09:22.945816Z",
     "start_time": "2025-03-03T07:09:22.940657Z"
    }
   },
   "cell_type": "code",
   "source": [
    "df_obj.loc[0,'b']=np.nan  # 将DataFrame中cloth='b'且size=1的元素设为NaN\n",
    "print(df_obj)\n",
    "print('-'*50)\n",
    "print(df_obj.min(axis=0,skipna=True))\n",
    "\"\"\"\n",
    "df_obj.min() 是用于计算 DataFrame 对象 df_obj 中元素最小值的方法\n",
    "skipna 是一个布尔类型的参数，其取值可以为 True 或者 False，主要用于控制在计算统计量（如最小值、最大值、平均值等）时是否跳过缺失值（NaN）。具体解释如下：\n",
    "skipna = True：这是该参数的默认值。当设置为 True 时，在计算统计量的过程中会自动忽略缺失值（NaN）。也就是说，计算仅基于非缺失值的数据进行。\n",
    "skipna = False：当设置为 False 时，在计算统计量时不会跳过缺失值。如果数据中存在缺失值，那么最终的计算结果将为 NaN。\n",
    "\"\"\""
   ],
   "id": "5546a422242d7001",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth         a         b         c         d\n",
      "size                                         \n",
      "0     -1.518355       NaN  0.913146  0.467908\n",
      "1      1.438618  0.675709  0.082567 -0.816552\n",
      "2      2.718638  1.915683  0.407188 -0.089726\n",
      "--------------------------------------------------\n",
      "cloth\n",
      "a   -1.518355\n",
      "b    0.675709\n",
      "c    0.082567\n",
      "d   -0.816552\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-03-03T07:15:41.715936Z",
     "start_time": "2025-03-03T07:15:41.708935Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(df_obj.describe())\n",
    "\"\"\"\n",
    "describe() 方法会对数据进行快速统计分析，生成一系列描述性统计指标，帮助用户快速了解数据的基本特征，如数据的中心趋势（均值、中位数等）、离散程度（标准差、四分位数等）。\n",
    "\"\"\""
   ],
   "id": "bf41d2fe2ac5ba5c",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth         a         b         c         d\n",
      "count  3.000000  2.000000  3.000000  3.000000\n",
      "mean   0.879634  1.295696  0.467634 -0.146123\n",
      "std    2.173103  0.876794  0.418575  0.644084\n",
      "min   -1.518355  0.675709  0.082567 -0.816552\n",
      "25%   -0.039869  0.985703  0.244878 -0.453139\n",
      "50%    1.438618  1.295696  0.407188 -0.089726\n",
      "75%    2.078628  1.605689  0.660167  0.189091\n",
      "max    2.718638  1.915683  0.913146  0.467908\n"
     ]
    }
   ],
   "execution_count": 13
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
